package p.rn.owner;

import java.io.File;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

import org.apache.commons.io.FileUtils;

import p.rn.util.FileVistor;

public class WebApp {

	/**
	 * @param args
	 * @throws IOException
	 */
	public static void main(String[] args) throws IOException {
		if (args.length < 2) {
			System.out.println("webapp pathToWebApp config [ignoreJarConfig]");
			return;
		}
		File webApp = new File(args[0]);
		File config = new File(args[1]);
		File jarIgnore = args.length > 2 ? new File(args[2]) : null;
		File clz = new File(webApp, "WEB-INF/classes");
		File tmpClz = new File(webApp, "WEB-INF/tmp-classes");
		final ReOwner ro = new ReOwner().withConfig(config);
		if (tmpClz.exists()) {
			FileUtils.deleteDirectory(tmpClz);
		}
		FileUtils.copyDirectory(clz, tmpClz);
		System.out.println("ReOwner from [" + tmpClz + "] to [" + clz + "]");
		ro.reOwner(tmpClz, clz);
		FileUtils.deleteDirectory(tmpClz);
		File tmpLib = new File(webApp, "WEB-INF/Nlib");
		final File lib = new File(webApp, "WEB-INF/lib");
		final Set<String> ignores = new HashSet<String>();
		if (jarIgnore != null && jarIgnore.exists()) {
			ignores.addAll(FileUtils.readLines(jarIgnore, "UTF-8"));
		} else {
			System.out.println("ignoreJarConfig ignored");
		}
		if (tmpLib.exists()) {
			FileUtils.deleteDirectory(tmpLib);
		}
		FileUtils.copyDirectory(lib, tmpLib);
		FileVistor fv = new FileVistor(tmpLib) {
			@Override
			public void vistFile(File file) {
				final String filename = file.getName();
				if (filename.endsWith(".jar")) {
					boolean ignore = false;
					for (String i : ignores) {
						if (filename.startsWith(i)) {
							ignore = true;
							break;
						}
					}
					if (!ignore) {
						File nJar = new File(lib, filename);
						System.out.println("ReOwner from [" + file + "] to [" + nJar + "]");
						ro.reOwner(file, nJar);
					}
				}
			}
		};
		fv.vist();
		FileUtils.deleteDirectory(tmpLib);
	}
}
